﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace Card.Manager
{
    public partial class TemplateEdit : BasePage
    {
        #region 属性
        public int TemplateID
        {
            get
            {
                int _id = 0;
                if (Request.QueryString["tid"] != null && int.TryParse(Request.QueryString["tid"], out _id))
                {
                    return _id;
                }

                return _id;
            }
        }

        private List<BAF.Entity.LookupValue> _FontFamily = null;
        /// <summary>
        /// 字符样式
        /// </summary>
        public List<BAF.Entity.LookupValue> FontFamily
        {
            get
            {
                if (_FontFamily == null)
                {
                    this._FontFamily = Card.Common.LookUpCache.GetLookupValues(CONST.LOOKUP_TYPE.FONT_FAMILY);
                }
                return _FontFamily;
            }
        }
        #endregion

        #region 事件

        protected override void OnInit(EventArgs e)
        {
            this.rptFrontFieldList.ItemDataBound += new RepeaterItemEventHandler(rptFrontFieldList_ItemDataBound);
            this.rptFrontFieldList.ItemCommand += new RepeaterCommandEventHandler(rptFieldList_ItemCommand);
            this.rptBackFieldList.ItemDataBound += new RepeaterItemEventHandler(rptBackFieldList_ItemDataBound);
            this.rptBackFieldList.ItemCommand += new RepeaterCommandEventHandler(rptFieldList_ItemCommand);
            this.btnSaveFLogo.Click += new EventHandler(btnSaveFLogo_Click);
            this.btnSaveBLogo.Click += new EventHandler(btnSaveBLogo_Click);
            this.lbtnDeleteBLogo.Click += new EventHandler(lbtnDeleteLogo_Click);
            this.lbtnDeleteFLogo.Click += new EventHandler(lbtnDeleteLogo_Click);
            base.OnInit(e);
        }

        void lbtnDeleteLogo_Click(object sender, EventArgs e)
        {
            string faceType = ((LinkButton)sender).CommandArgument.ToString();
            if (string.Compare("F", faceType) == 0)
            {
                BLL.TemplateLogoManager.Delete(this.TemplateID, CONST.CARD_FACE_TYPE.FRONT, this.CPassport);
            }
            else if (string.Compare("B", faceType) == 0)
            {
                BLL.TemplateLogoManager.Delete(this.TemplateID, CONST.CARD_FACE_TYPE.BACK, this.CPassport);
            }
            Response.Redirect(string.Format("TemplateEdit.aspx?tid={0}", this.TemplateID));
        }

        void btnSaveBLogo_Click(object sender, EventArgs e)
        {
            Entity.TemplateLogo logo = new Card.Entity.TemplateLogo();
            logo.TemplateID = this.TemplateID;
            logo.ImageType = CONST.CARD_FACE_TYPE.BACK;
            logo.Logo = this.txtLogoB.Text.Trim();
            logo.Width = decimal.Parse(this.txtLogoWidthB.Text);
            logo.Height = decimal.Parse(this.txtLogoHeightB.Text);
            logo.PosX = decimal.Parse(this.txtLogoLeftB.Text);
            logo.PosY = decimal.Parse(this.txtLogoTopB.Text);

            if (BLL.TemplateLogoManager.Save(logo, this.CPassport))
            {
                this.MessageBox("保存成功！");
            }
            this.BindBackLogo();
        }

        void btnSaveFLogo_Click(object sender, EventArgs e)
        {
            Entity.TemplateLogo logo = new Card.Entity.TemplateLogo();
            logo.TemplateID = this.TemplateID;
            logo.ImageType = CONST.CARD_FACE_TYPE.FRONT;
            logo.Logo = this.txtLogoF.Text.Trim();
            logo.Width = decimal.Parse(this.txtLogoWidthF.Text);
            logo.Height = decimal.Parse(this.txtLogoHeightF.Text);
            logo.PosX = decimal.Parse(this.txtLogoLeftF.Text);
            logo.PosY = decimal.Parse(this.txtLogoTopF.Text);

            if (BLL.TemplateLogoManager.Save(logo, this.CPassport))
            {
                this.MessageBox("保存成功！");
            }
            this.BindFrontLogo();
        }

        void rptBackFieldList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            this.ItemDataBound(sender, e, "back");
        }

        void rptFieldList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            bool result = false;
            string t = e.CommandArgument.ToString();
            if (string.Compare(e.CommandName, "UPDATE") == 0)
            {
                result = this.SaveRptItem(e.Item, t, false);
            }
            else if (string.Compare(e.CommandName, "NEW") == 0)
            {
                result = this.SaveRptItem(e.Item, t, true);
            }
            else if (string.Compare(e.CommandName, "SAVEALL") == 0)
            {
                RepeaterItemCollection items = string.Compare(t, "front") == 0 ? rptFrontFieldList.Items : rptBackFieldList.Items;

                foreach (RepeaterItem item in items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        result = this.SaveRptItem(item, t, false);
                    }
                }
            }
            else if (string.Compare(e.CommandName, "DELETE") == 0)
            {
                Label lblID = e.Item.FindControl("lblID") as Label;
                int fieldID = 0;
                if (int.TryParse(lblID.Text, out fieldID))
                {
                    BLL.TemplateFieldManager.Delete(fieldID, null);   
                }
            }

            if (result)
            {
                this.MessageBox("保存成功！");
            }
            if (string.Compare(t, "front") == 0)
            {
                this.BindRptFront();
            }
            else
            {
                this.BindRptBack();
            }
        }

        void rptFrontFieldList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            this.ItemDataBound(sender, e, "front");
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.DoInit();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtName.Text.Trim()))
            {
                this.MessageBox("请输入模版名称！");
                return;
            }

            Card.Entity.Template template = BLL.TemplateManager.GetEntity(this.TemplateID, this.CPassport);
            if (template == null)
            {
                template = new Card.Entity.Template();
            }
            template.ID = this.TemplateID;
            template.Name = this.txtName.Text.Trim();
            template.TypeCode = this.dropType.SelectedValue;
            template.Style = this.rdbStyle.SelectedValue;
            template.Color = this.dropColor.SelectedValue;
            template.Status = this.rdbStatus.SelectedValue;

            if (this.TemplateID > 0)
            {
                if (BLL.TemplateManager.Update(template, CPassport))
                {
                    this.MessageBox("保存成功！");
                }
            }
            else
            {
                template.ID = BAF.BLL.SYSSequenceManager.GetSequence(CONST.SEQUENCE_CODE.TEMPLATE_ID, Passport);
                template.FrontImage = "20121200F.png";
                template.BackImage = "20121200B.png";
                template.Status = CONST.TEMPLATE_STATUS.BUILDING;
                if (BLL.TemplateManager.Add(template, this.CPassport))
                {
                    this.MessageBox("保存成功！", "TemplateEdit.aspx?tid=" + template.ID);
                }
            }
        }
        #endregion

        #region 方法
        private void DoInit()
        {
            this.BindDropDownList();
            if (this.TemplateID > 0)
            {
                Card.Entity.Template template = BLL.TemplateManager.GetEntity(this.TemplateID, this.CPassport);
                if (template != null)
                {
                    this.txtName.Text = template.Name;
                    Card.Utility.ControlUtility.SelectItemByValue(this.dropColor, template.Color);
                    Card.Utility.ControlUtility.SelectItemByValue(this.dropType, template.TypeCode);
                    Card.Utility.ControlUtility.SelectItemByValue(this.rdbStyle, template.Style);
                    Card.Utility.ControlUtility.SelectItemByValue(this.rdbStatus, template.Status);
                    if (string.Compare(template.Style, CONST.TEMPLATE_STYLE.VERTICAL, true) == 0)
                    {
                        this.card_front.Attributes.Add("class", "card_vertical");
                        this.card_back.Attributes.Add("class", "card_vertical");
                    }
                    else
                    {
                        this.card_front.Attributes.Add("class", "card");
                        this.card_back.Attributes.Add("class", "card");
                    }
                    this.frontImg.ImageUrl = Card.Utility.ImageUtilty.GetTemplateThumbImagePath(template.FrontImage);
                    this.backImg.ImageUrl = Card.Utility.ImageUtilty.GetTemplateThumbImagePath(template.BackImage);
                    this.BindRptFront();
                    this.BindRptBack();
                }
                this.BindFrontLogo();
                this.BindBackLogo();
            }
            else
            {
                this.fields.Visible = false;
            }
        }

        private void BindFrontLogo()
        {
            Entity.TemplateLogo fLogo = BLL.TemplateLogoManager.GetEntity(this.TemplateID, CONST.CARD_FACE_TYPE.FRONT, this.CPassport);
            if (fLogo != null)
            {
                this.txtLogoF.Text = fLogo.Logo;
                this.SetTextBoxVal(this.txtLogoHeightF, fLogo.Height.ToString());
                this.SetTextBoxVal(this.txtLogoWidthF, fLogo.Width.ToString());
                this.SetTextBoxVal(this.txtLogoTopF, fLogo.PosY.ToString());
                this.SetTextBoxVal(this.txtLogoLeftF, fLogo.PosX.ToString());
                this.FLogo.ImageUrl = Card.Utility.ImageUtilty.GetLogoPath(fLogo.Logo);
                this.ltlFLogo.Text = string.Format("<img id='FLImg' style='border:0px;z-index:98;width:{0}px;height:{1}px;top:{2}px;left:{3}px;position: absolute;'  w='{0}' h='{1}' ow='{0}' oh='{1}' x='{2}' y='{3}' src='{4}' class='mplogo' />",
                fLogo.Width, fLogo.Height, fLogo.PosY, fLogo.PosX, this.FLogo.ImageUrl);
            }
            else
            {
                this.txtLogoF.Text = string.Empty;
                this.SetTextBoxVal(this.txtLogoHeightF, "50");
                this.SetTextBoxVal(this.txtLogoWidthF, "50");
                this.SetTextBoxVal(this.txtLogoTopF, "50");
                this.SetTextBoxVal(this.txtLogoLeftF, "50");
                this.FLogo.ImageUrl = "/transparent.gif";
                this.ltlFLogo.Text = string.Empty;
            }
        }

        private void BindBackLogo()
        {
            Entity.TemplateLogo bLogo = BLL.TemplateLogoManager.GetEntity(this.TemplateID, CONST.CARD_FACE_TYPE.BACK, this.CPassport);
            if (bLogo != null)
            {
                this.txtLogoB.Text = bLogo.Logo;
                this.SetTextBoxVal(this.txtLogoHeightB, bLogo.Height.ToString());
                this.SetTextBoxVal(this.txtLogoWidthB, bLogo.Width.ToString());
                this.SetTextBoxVal(this.txtLogoTopB, bLogo.PosY.ToString());
                this.SetTextBoxVal(this.txtLogoLeftB, bLogo.PosX.ToString());
                this.BLogo.ImageUrl = Card.Utility.ImageUtilty.GetLogoPath(bLogo.Logo);
                this.ltlBLogo.Text = string.Format("<img id='BLImg' style='border:0px;z-index:98;width:{0}px;height:{1}px;top:{2}px;left:{3}px;position: absolute;' w='{0}' h='{1}'  ow='{0}' oh='{1}' x='{2}' y='{3}'  src='{4}' class='mplogo' />",
                bLogo.Width, bLogo.Height, bLogo.PosY, bLogo.PosX, this.BLogo.ImageUrl);
            }
            else
            {
                this.txtLogoF.Text = string.Empty;
                this.SetTextBoxVal(this.txtLogoHeightB, "50");
                this.SetTextBoxVal(this.txtLogoWidthB, "50");
                this.SetTextBoxVal(this.txtLogoTopB, "50");
                this.SetTextBoxVal(this.txtLogoLeftB, "50");
                this.BLogo.ImageUrl = "/transparent.gif";
                this.ltlBLogo.Text = string.Empty;
            }
        }

        private void BindRptFront()
        {
            DataTable dtFields = BLL.TemplateFieldManager.GetFieldList(this.TemplateID, CONST.CARD_FACE_TYPE.FRONT, this.CPassport);

            this.rptFrontFieldList.DataSource = dtFields;
            this.rptFrontFieldList.DataBind();
        }

        private void BindRptBack()
        {
            DataTable dtFields = BLL.TemplateFieldManager.GetFieldList(this.TemplateID, CONST.CARD_FACE_TYPE.BACK, this.CPassport);

            this.rptBackFieldList.DataSource = dtFields;
            this.rptBackFieldList.DataBind();
        }

        private void BindDropDownList()
        {
            List<BAF.Entity.LookupValue> lstTemplateType = Card.Common.LookUpCache.GetLookupValues(CONST.LOOKUP_TYPE.TEMPLATE_TYPE);
            List<BAF.Entity.LookupValue> lstColor = Card.Common.LookUpCache.GetLookupValues(CONST.LOOKUP_TYPE.TEMPLATE_COLOR);
            Card.Utility.ControlUtility.BindListControl<BAF.Entity.LookupValue>(this.dropColor, lstColor, "Description", "LookupCode", false);
            Card.Utility.ControlUtility.BindListControl<BAF.Entity.LookupValue>(this.dropType, lstTemplateType, "Value", "LookupCode", false);
        }

        private bool SaveRptItem(RepeaterItem item, string t, bool isNew)
        {
            Label lblID = item.FindControl("lblID") as Label;
            TextBox txtSort = item.FindControl("txtSort_" + t) as TextBox;
            DropDownList dropFontFamily = item.FindControl("dropFontFamily_" + t) as DropDownList;
            TextBox txtColor = item.FindControl("txtColor_" + t) as TextBox;
            TextBox txtFontSize = item.FindControl("txtFontSize_" + t) as TextBox;
            TextBox txtTop = item.FindControl("txtTop_" + t) as TextBox;
            TextBox txtLeft = item.FindControl("txtLeft_" + t) as TextBox;
            RadioButtonList rdbDirection = item.FindControl("rdbDirection_" + t) as RadioButtonList;
            TextBox txtContent = item.FindControl("txtContent_" + t) as TextBox;

            if (lblID != null
                && txtSort != null
                && dropFontFamily != null
                && txtColor != null
                && txtFontSize != null
                && txtTop != null
                && txtLeft != null
                && rdbDirection != null
                && txtContent != null
                && BAF.Utility.ValidationHelper.IsNumber(lblID.Text))
            {
                int fieldID = 0;
                if (int.TryParse(lblID.Text, out fieldID))
                {
                    Card.Entity.TemplateField field = isNew ? new Card.Entity.TemplateField() : BLL.TemplateFieldManager.GetEntity(fieldID, null);

                    if (field != null)
                    {
                        field.Sort = GetIntVal(txtSort, field.Sort);
                        field.FontFamily = dropFontFamily.SelectedValue;
                        field.Color = string.IsNullOrEmpty(txtColor.Text) ? "#000000" : txtColor.Text.Trim();
                        field.FontSize = GetDecimalVal(txtFontSize, field.FontSize);
                        field.PosX = GetDecimalVal(txtLeft, field.PosX);
                        field.PosY = GetDecimalVal(txtTop, field.PosY);
                        field.Direction = rdbDirection.SelectedValue;
                        field.Content = txtContent.Text.Trim();
                        field.ImageType = string.Compare(t, "front") == 0 ? CONST.CARD_FACE_TYPE.FRONT : CONST.CARD_FACE_TYPE.BACK;
                        field.TemplateID = this.TemplateID;

                        return BLL.TemplateFieldManager.Save(field, this.CPassport);
                    }
                }
            }
            return false;
        }

        private void ItemDataBound(object sender, RepeaterItemEventArgs e, string t)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                DropDownList dropFontFamily = e.Item.FindControl("dropFontFamily_" + t) as DropDownList;
                RadioButtonList rdbDirection = e.Item.FindControl("rdbDirection_" + t) as RadioButtonList;
                if (dropFontFamily != null && rdbDirection != null)
                {
                    Card.Utility.ControlUtility.SelectItemByValue(dropFontFamily, drv["FONT_FAMILY"].ToString());
                    Card.Utility.ControlUtility.SelectItemByValue(rdbDirection, drv["DIRECTION"].ToString());
                }
            }
        }

        private Decimal GetDecimalVal(TextBox txt, decimal defaultVal)
        {
            decimal val = defaultVal;
            if (!decimal.TryParse(txt.Text.Trim(), out val))
            {
                txt.Text = defaultVal.ToString();
            }

            return val;
        }

        private int GetIntVal(TextBox txt, int defaultVal)
        {
            int val = defaultVal;
            if (!int.TryParse(txt.Text.Trim(), out val))
            {
                txt.Text = defaultVal.ToString();
            }

            return val;
        }

        private void SetTextBoxVal(TextBox tb, string val)
        {
            tb.Text = val;
            tb.Attributes.Add("h", val);
        }
        #endregion
    }
}
